<template>
  <div class="app-container">
    <el-collapse v-model="activeNames">
      <el-collapse-item name="1">
        <template slot="title">
          <MmvTitle title="订单信息"></MmvTitle>
        </template>

        <el-descriptions class="margin-top margin-bottom" :column="3" border>
          <el-descriptions-item label-class-name="my-descriptions-label" >
            <template slot="label"> 订单编号</template>
            {{ detail.orderInfo.orderNo }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" >
            <template slot="label"> 订单状态</template>
            <dict-tag :options="dict.type.sys_order_status" :value="detail.orderInfo.orderStatus"/>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" >
            <template slot="label"> 取车类型</template>
            {{ {1: '到店取还车', 3: '上门送取车', 4: '上门送车', 5: '上门取车',}[Number(detail.orderInfo.rentalType)] }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" >
            <template slot="label"> 预约取车时间</template>
            {{ detail.orderInfo.rentalStartTime }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" >
            <template slot="label"> 预约还车时间</template>
            {{ detail.orderInfo.rentalEndTime }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" >
            <template slot="label"> 预约租期（天）</template>
            {{ detail.orderInfo.leaseDays }}
          </el-descriptions-item>

          <template v-if="detail.orderInfo.orderStatus>3&&detail.orderInfo.orderStatus<10">
            <el-descriptions-item label-class-name="my-descriptions-label" >
              <template slot="label"> 实际取车时间</template>
              {{ detail.orderInfo.actualStartTime }}
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label" >
              <template slot="label"> 实际还车时间</template>
              {{ detail.orderInfo.actualEndTime }}
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label" >
              <template slot="label"> 实际租期（天）</template>
              {{ detail.orderInfo.actualLeaseDays }}
            </el-descriptions-item>
          </template>

          <el-descriptions-item label-class-name="my-descriptions-label"  span="3" v-if="detail.orderInfo.rentalType==3||detail.orderInfo.rentalType==4">
            <template slot="label"> 预约取车地址</template>
            {{ detail.orderInfo.takeAddress }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label"  span="3" v-if="detail.orderInfo.rentalType==3||detail.orderInfo.rentalType==5">
            <template slot="label"> 预约还车地址</template>
            {{ detail.orderInfo.alsoAddress }}
          </el-descriptions-item>

          <el-descriptions-item label-class-name="my-descriptions-label" >
            <template slot="label"> 预约取车门店</template>
            {{ detail.orderInfo.reserveTakeStoreName }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" >
            <template slot="label"> 预约还车门店</template>
            {{ detail.orderInfo.reserveAlsoStoreName }}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" >
            <template slot="label"> 预定车型</template>
            {{ detail.orderInfo.modelName }}
          </el-descriptions-item>


          <template v-if="detail.orderInfo.orderStatus>3&&detail.orderInfo.orderStatus<10">
            <el-descriptions-item label-class-name="my-descriptions-label" >
              <template slot="label"> 实际取车门店</template>
              {{ detail.orderInfo.takeStoreName }}
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label" >
              <template slot="label"> 实际还车门店</template>
              {{ detail.orderInfo.orderStatus > 4 ? detail.orderInfo.alsoStoreName : "" }}
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label" >
              <template slot="label"> 实际车型</template>
              {{ detail.orderInfo.actualModelName }}
            </el-descriptions-item>
          </template>
        </el-descriptions>
      </el-collapse-item>
      <el-collapse-item name="2">
        <template slot="title">
          <MmvTitle title="客户信息"></MmvTitle>
        </template>
        <MemberDetail :detail="detail.customerInfo"></MemberDetail>
      </el-collapse-item>
    </el-collapse>



    <el-form  label-width="120px" label-position="right" size="small">
    <MmvTitle title="续租信息"></MmvTitle>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="还车时间" prop="rentalEndTime">
            <el-date-picker  v-model="rentalEndTime"  :picker-options="{disabledDate}" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                             placeholder="选择日期" style="width:220px;margin-right:15px" @change="rentalEndTimeChange"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="form.leaseDays">
          <div style="line-height: 33px;font-weight: 600;font-size: 16px;">续租时长:{{form.leaseDays}}天</div>
        </el-col>

        <el-col :span="8">
          <el-form-item label="签署续租合同" prop="openContract">
            <el-switch v-model="form.openContract"></el-switch>
          </el-form-item>
        </el-col>

      </el-row>
    <MmvTitle title="续租费用"></MmvTitle>
      <el-row :gutter="15">
        <el-col :span="24">
          <el-table :data="form.chargeItemsVo" border>
            <el-table-column label="收费项名称" prop="chargeProjectName" align="center">
              <template slot-scope="{ row }">
                <el-input v-if="row.canEdit==3" v-model="row.chargeProjectName"></el-input>
                <span v-else >{{ row.chargeProjectName }}</span>
              </template>
            </el-table-column>

            <el-table-column label="单价" prop="unitPrice" align="center">
              <template slot-scope="{ row }">
                <el-input    v-model="row.unitPrice"  @keyup.native="row.unitPrice= oninput(row.unitPrice, 2);jisuanMoney(row)"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="收费类型" prop="chargeItemsType" align="center">
              <template slot-scope="{ row }">
                <el-select  v-if="row.canEdit==3" v-model="row.chargeItemsType" clearable  @change="changeType(row)">
                  <el-option label="按次" :value="1"></el-option>
                  <el-option label="按天" :value="2"></el-option>
                  <el-option label="按个" :value="6"></el-option>
                </el-select>
                <span v-else> {{{1: '按次', 2: '按天', 3: '按里程', 6: '按个'}[Number(row.chargeItemsType)] }}</span>

              </template>
            </el-table-column>

            <el-table-column label="数目" prop="number" align="center">
              <template slot-scope="{ row }">
                <el-input v-if="row.chargeItemsType!=2&&row.canEdit>1" v-model="row.number" @keyup.native="row.number= oninput(row.number, 0);row.chargeMoney=(row.unitPrice*row.number).toFixed(2)"></el-input>
                <span v-else> {{row.number}}</span>
              </template>
            </el-table-column>


            <el-table-column label="费用" prop="chargeMoney" align="center">
              <template slot-scope="{ row }">
                {{ Number(row.chargeMoney).toFixed(2) }} 元
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="{ row }">
<!--                <el-button v-if="row.canEdit != 1&&(row.isOptional==1||row.canEdit==3)" type="danger" icon="el-icon-delete" size="mini" @click="deleteChargingItems(row)"></el-button>-->
                <el-button v-if="row.canEdit == 3" type="danger" icon="el-icon-delete" size="mini" @click="deleteChargingItems(row)"></el-button>
                <el-switch v-model="row.selected"  v-if="row.canEdit == 2 &&row.isOptional == 1" ></el-switch>

                <el-popover placement="right" trigger="click"  v-if="row.isRent==1">
                  <div class="ant-popover-inner-content">
                    <div class="fee-detail-wrapper">
                      <div class="day-item" v-for="(item,index) in form.planPriceVoList" :key="index">
                        <div class="date-weekname">
                          <div>{{ item.time }}</div>
                          <div>{{ item.dateOfWeek }}</div>
                        </div>
                        <div class="price-color word-break">¥{{item.price}}</div>
                      </div>
                    </div>
                  </div>
                  <el-button slot="reference" icon="el-icon-search" type="text">价格日历</el-button>
                </el-popover>

              </template>
            </el-table-column>
          </el-table>
          <el-col :span="24" style="text-align: center;margin-bottom: 10px">
            <el-button icon="el-icon-plus" @click="addChargingItems">添加收费项</el-button>
          </el-col>
          <br>
        </el-col>
        <el-col :span="24">
          <el-form-item label="续租费用合计" required>
            ¥<span style="color: red;font-weight: 600;font-size: 20px;"> {{rent}} </span>元
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-form-item v-if="showMsg">
          <div style="color: red">{{msg}}</div>
        </el-form-item>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: end;">
      <el-button @click="closeDiolog">取消</el-button>
      <el-button type="primary" :loading="submitBtnLoading" @click="submitData">确定</el-button>
    </div>

    <!--   续租成功   -->
    <el-dialog title="续租成功" :visible.sync="scheduled" style="margin-top: 20vh !important;" width="800px" destroy-on-close append-to-body @close="closeDiolog(true)">
      <el-form label-width="125px" label-position="right" class="scheduled">
        <el-row :gutter="15">
          <el-col :span="8">
            <div style="padding: 20px 50px 0px 50px">
              <el-image class="preview" :src="overPng" fit="contain"></el-image>
            </div>
            <div style="text-align: center;font-size: 20px;color: #027db4;">预定成功</div>
          </el-col>
          <el-col :span="16">
            <el-form-item label="订单编号:">{{ scheduledData.orderNo }}</el-form-item>
            <el-form-item label="客户姓名:">{{ scheduledData.memberName }}</el-form-item>
            <el-form-item label="预定时间:">
              {{ parseTime(scheduledData.rentalStartTime) + '～' + parseTime(scheduledData.rentalEndTime) }}
            </el-form-item>
            <el-form-item label="预定车型:">{{ scheduledData.modelName }}</el-form-item>
            <el-form-item label="取车门店:">{{ scheduledData.reserveTakeStoreName }}</el-form-item>
            <el-form-item label="还车门店:">{{ scheduledData.reserveAlsoStoreName }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="scheduled=false;closeDiolog(true)">返回订单列表</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  renewRecordInfo,
  renewalFee,
  renewRecordEdit, renewalInspection
} from '@/api/order/index';
import MmvTitle from '@/components/MmvUI/MmvTitle.vue';
import {parseTime} from "@/utils";
import MemberDetail from "@/views/components/memberDetail";

export default {
  components: {
    MmvTitle,
    MemberDetail
  },
  dicts: ['sys_pay_type', 'order_payStatus', 'charge_type', 'refund_type', 'sys_order_status', 'document_type'],
  props: ['orderNo','id'],
  data() {
    return {

      showMsg: false,
      msg: '',

      nowId: null,
      activeNames: [],

      detail: {
        orderInfo: {},
        customerInfo: {},
      },
      renewRecord : {},
      form:{
        rentalEndTime:null,
        leaseDays:null,
        payType:1,
        payWay:1,
        chargeItemsVo:[],
        planPriceVoList: [],
        openContract:false
      },
      rentalEndTime:null,
      loading: true,
      submitBtnLoading: false,
      scheduled: false,
      scheduledData:{},
      overPng: require('@/assets/images/over.png'),
    }
  },
  watch: {

  },
  computed: {
    rent() {
      let total = 0;
      this.form.chargeItemsVo.forEach(val => {
        if(val.selected){
          total += Number(val.chargeMoney)
        }
      });
      return total.toFixed(2) || 0;
    }
  },
  filters: {
    memberType(val) {
      return {
        1: '企业',
        2: '个人',
      }[Number(val)] || '';
    },
    memberSource(val) {
      return {
        1: '搜索',
        2: '分享',
        3: '扫码',
        4: '手动录入',
      }[Number(val)] || '';
    },
    imageUrl(url) {
      return process.env.VUE_APP_BASE_IMAGE_URL + url
    },
  },
  mounted() {
    this.costDetail();
  },
  methods: {
    rentalEndTimeChange(val) {
      if (val) {
        this.form.rentalEndTime=val
        this.renewalFee()
      }else{
        this.form={
          rentalEndTime:null,
          leaseDays:null,
          payType:1,
          payWay:1,
          chargeItemsVo:[]
        }
      }
    },
    disabledDate(date) {
     let time= parseTime(date,"{y}-{m}-{d}")+" "+parseTime(this.detail.orderInfo.rentalEndTime,"{h}:{i}:{s}");
      return new Date(this.detail.orderInfo.rentalEndTime).getTime() >= new Date(time).getTime() + 24 * 60 * 60 * 1000;
    },
    closeDiolog() {
      this.$emit('close');
    },
    renewalFee() {
      renewalFee({orderNo:this.orderNo,takeAlsoTime:this.rentalEndTime,renewRecordId:this.id}).then(response => {
        this.form.leaseDays = response.data?.days || 0; // 租期
        const chargingItemsVoList = response.data?.chargingItemsVoList || []; // 上门 取车 还车 异店 费用
        const noMandatoryOtherCostList = response.data?.noMandatoryOtherCostList || []; // 其他费用—非必选

        this.form.planPriceVoList =response.data?.planPriceVoList||[]//价格日历
        let arr = [...chargingItemsVoList,...noMandatoryOtherCostList];
        this.form.chargeItemsVo=[];
        for (let item of arr){
          this.form.chargeItemsVo.push({
            ...item,
            selected:item.canEdit !== 2||item.isOptional !== 1,
          })
        }
      });
    },
    dateOfWeek(val) {
      return {
        1: '星期一',
        2: '星期二',
        3: '星期三',
        4: '星期四',
        5: '星期五',
        6: '星期六',
        7: '星期日',
      }[Number(val)] || '';
    },
    costDetail() {
      renewRecordInfo(this.id).then(response => {
        this.detail = response.data || {};
        this.detail.customerInfo.labelClassify = response.data.customerInfo.labelClassify.split(',')

        this.renewRecord = response.data.renewRecord;
        this.detail.orderInfo.rentalEndTime = this.renewRecord.beforeTime

        this.form.leaseDays = this.renewRecord.renewDays || 0; // 租期
        this.rentalEndTime = this.renewRecord.afterTime ;
        this.form.rentalEndTime = this.renewRecord.afterTime;

        this.form.planPriceVoList = [] ;//价格日历
        for(let item of this.renewRecord.cost.orderPriceCalendars){
          this.form.planPriceVoList.push({
            dateOfWeek:this.dateOfWeek(item.dateOfWeek),
            price:item.price,
            time:item.sameDay,
            type : 1
          })
        }

        this.form.chargeItemsVo=[];
        for (let item of this.renewRecord.cost.orderChargingItems){
          this.form.chargeItemsVo.push({
            ...item,
            selected:item.canEdit !== 2||item.isOptional !== 1,
          })
        }

        this.loading = false
      });
    },
    addChargingItems() {
      this.form.chargeItemsVo.push({
        chargeProjectName: '',
        unitPrice: 0,
        chargeItemsType: 1,
        number: 1,
        canEdit: 3,
        chargeMoney: 0,
        selected: true,
      })
    },
    jisuanMoney(row) {
      let chargeMoney = (row.unitPrice * row.number)||0;
      if (row.upperLimitOfAmount!=null&&row.upperLimitOfAmount >= 0 && chargeMoney > row.upperLimitOfAmount) {
        row.chargeMoney = row.upperLimitOfAmount.toFixed(2);
      } else {
        row.chargeMoney = chargeMoney.toFixed(2);
      }
    },
    changeType(row){
      if(row.chargeItemsType==2){
        row.number=this.form.leaseDays
        row.chargeMoney=(row.unitPrice*row.number).toFixed(2)
      }else{
        row.number=1
        row.chargeMoney=(row.unitPrice*row.number).toFixed(2)
      }
    },
    deleteChargingItems(row) {
      const index = this.form.chargeItemsVo.map(f => f.chargeProjectName).indexOf(row.chargeProjectName);
      this.form.chargeItemsVo.splice(index, 1)
    },
    submitData() {
      if(!this.rentalEndTime){
        this.$message.error('请选择续租还车时间')
        return;
      }
      if(new Date(this.detail.orderInfo.rentalEndTime).getTime()>=new Date(this.rentalEndTime).getTime()){
        this.$message.error('续租还车时间必须大于预约还车时间')
        return;
      }
      for (let item of this.form.chargeItemsVo) {
        if(!item.chargeProjectName){
          this.$message.error('费用项名称不能为空')
          return false;
        }
        if(!item.unitPrice){
          item.unitPrice=0
        }
        if(!item.chargeItemsType){
          this.$message.error('请选择费用类型')
          return false;
        }
        if(!item.number){
          item.number=1
        }
      }
      let chargeItemsVo = this.form.chargeItemsVo.filter(i => {
        return i.selected && i.number > 0
      })//收费项
      let data ={
        orderNo:this.orderNo,
        rent:this.rent,
        renewRecordId:this.id,
        ...this.form,
        chargeItemsVo : chargeItemsVo
      }

      this.submitBtnLoading = true
      renewalInspection(data).then(res => {
        switch (res.data.code){
          case 0:
            this.doRenewal(data);
            break;
          case 1:

            this.submitBtnLoading = false
            this.showMsg=true;
            this.msg = res.data.msg;
            break;
          case 2:

            this.submitBtnLoading = false
            this.$confirm(res.data.msg, '提示', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.doRenewal(data);
            })
            break;
        }
      })
    },
    doRenewal(data){
      this.submitBtnLoading = false
      renewRecordEdit(data).then(response => {
        this.$message.success(response.msg);
        this.closeDiolog();
      }).finally(err=>{
        this.submitBtnLoading = false
      });
    },

  },

}
</script>
<style scoped>
.fee-detail-wrapper {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  max-width: 420px;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-box-pack: start;
  -ms-flex-pack: start;
  justify-content: flex-start;
  max-height: 400px;
  overflow-y: auto;
}
.day-item {
  width: 80px;
  text-align: center;
  margin-top: 10px;
}
.price-color {
  color: #ff8b26;
}


</style>
<style scoped>
/deep/ .my-content {
  width: 100px!important;
}
</style>
